package com.xja.controller;

import com.xja.pojo.Permissions;
import com.xja.pojo.Role;
import com.xja.service.PermissionService;
import com.xja.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@RequestMapping("/admin/role")
@Controller
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @RequestMapping("/list")
    public String list(Model model){
        List<Role> roles = roleService.findList();
        model.addAttribute("roles",roles);
        return "/admin/role/cate";
    }

    @RequestMapping("/toAdd")
    public String toAdd(Model model){
        List<Permissions> pList = permissionService.findList();
        model.addAttribute("pList",pList);
        return "/admin/role/add";
    }

    @RequestMapping("/add")
    public String add(Role role,Integer[] ps, Model model){
        //System.out.println("ps: "+ps);
        /*System.out.println(role);
        for(String s:ps)
            System.out.print(s+"  ");
        System.out.println();*/
        roleService.addRole(role,ps);
        return "redirect:list";




    }

    @RequestMapping("/toUpdate")
    public String toUpdate(Integer id,Model model){
        Role role = roleService.findRoleById(id);
        List<Permissions> pList1 = permissionService.findList();
        List<Permissions> pList2 = permissionService.findPermissionByRoleId(id);
        model.addAttribute("role",role);
        model.addAttribute("pList",pList1);
        String str ="";
        for(Permissions p:pList2)
            str+="-"+p.getId();
        //System.out.println(str);
        model.addAttribute("str",str);
        return "/admin/role/cateedit";
    }

    @RequestMapping("/update")
    public String update(Role role,Integer[] ps, Model model){
        roleService.updateRole(role,ps);
        return "redirect:list";
    }

    @RequestMapping("/delete")
    public String delete(Integer roleId){
        roleService.deleteRole(roleId);
        return "redirect:list";
    }
}
